/*
 * Licensed to the Apache Software Foundation (ASF) under one
 * or more contributor license agreements. See the NOTICE file
 * distributed with this work for additional information
 * regarding copyright ownership. The ASF licenses this file
 * to you under the Apache License, Version 2.0 (the
 * "License"); you may not use this file except in compliance
 * with the License. You may obtain a copy of the License at
 *
 *     http://www.apache.org/licenses/LICENSE-2.0
 *
 * Unless required by applicable law or agreed to in writing,
 * software distributed under the License is distributed on an
 * "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY
 * KIND, either express or implied. See the License for the
 * specific language governing permissions and limitations under the License.
 */

package opensocial.apps.friendforsale.command;

import opensocial.apps.common.AppContext;
import opensocial.apps.common.command.BaseCommand;
import opensocial.apps.friendforsale.model.Player;
import opensocial.apps.friendforsale.service.FriendDAOPersist;
import opensocial.apps.friendforsale.service.FriendPersist;

import org.apache.commons.chain.Context;
import org.apache.log4j.Logger;

/* the base command of friendsale,all other command must inherit this command*/

public abstract class FriendsaleBaseCommand extends BaseCommand {
  private static final Logger LOGGER = Logger
      .getLogger(FriendsaleBaseCommand.class);

  protected static FriendPersist persist = FriendDAOPersist.getInstance();
  protected String vid;
  protected String oid;
  protected String ctn;

  @Override
  public boolean pre(Context context) {
    if (super.pre(context) == NEXT) {
      vid = (String) context.get(AppContext.KEY_VIEWER_ID);
      oid = (String) context.get(AppContext.KEY_OWNER_ID);
      ctn = (String) context.get(AppContext.KEY_CONTAINER);
      if (vid == null) {
        LOGGER.error("viewer id is null");
        return END;
      }

      if (ctn == null) {
        LOGGER.error("container is null");
        return END;
      }

      if (oid == null) {
        LOGGER.error("target id is null");
        return END;
      }

      return NEXT;
    } else {
      return END;
    }
  }

  public Player getViewer() {
    return persist.load(ctn, vid);
  }

  public Player getOwner() {
    return persist.load(ctn, oid);
  }

  public Player getPlayer(String uid) {
    return persist.load(ctn, uid);
  }

}
